package com.xiaodong.reggie.controller;

import com.xiaodong.reggie.currency.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CurrencyController {

    @Value("${reggie.path}")
    private String basePath;

    //文件图片上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {

        String fileName = file.getOriginalFilename();

        String newName = fileName.substring(fileName.lastIndexOf("."));

        String name = UUID.randomUUID().toString() + newName;

        File path = new File(basePath);

        //判断目录是否存在
        if (!path.exists()) {
            path.mkdirs();
        }

        //将文件名转到指定位置
        try {
            file.transferTo(new File(basePath + name));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(name);

    }

    //文件下载
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {

        try {
            //文件输入流输入图片
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            //文件输出流输出图片 将图片写入到浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int num=0;
            byte [] bytes=new byte[1024];
            while ((num=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,num);
                outputStream.flush();
            }

            //关闭流
            fileInputStream.close();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
